import React, {
  useCallback,
  useMemo
} from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import './App.css';

import Header from '../common/Header'
import DepartDate from './DepartDate'
import HighSpeed from './HighSpeed'
import Journey from './Journey'
import Submit from './Submit'

import CitySelector from '../common/CitySelector'

// 引入actions
import {
  exchangeFromTo,
  showCitySelector,
  hideCitySelector,
  setSelectedCity,
  fetchCityData
} from './actions'
function App(props) {
  const {
    from,
    to,
    isCitySelectorVisible,
    cityData,
    isLoadingCItyData,
    dispatch
  } = props
  // 防止header 组件重新渲染
  const onBack = useCallback(() => {
    window.history.back()
  }, [])

  // const doExchangeFromTo = useCallback(() => {
  //   dispatch(exchangeFromTo())
  // }, [])
  // const doShowCitySelector = useCallback(m => {
  //   dispatch(showCitySelector(m))
  // }, [])

  // 批量把 useCallback 和 createAction 绑定在一起
  const cbs = useMemo(() => {
    return bindActionCreators({
      exchangeFromTo,
      showCitySelector,
    }, dispatch)
  })
  const citySelectorCbs = useMemo(() => {
    return bindActionCreators({
      onBack: hideCitySelector,
      fetchCityData,
      onSelect: setSelectedCity
    }, dispatch)
  }, [])

  return (

    <div>
      <div className='header-wrapper'>
        <Header title='火车票' onBack={onBack} />
      </div>
      <form className='form'>
        <Journey
          from={from}
          to={to}
          // exchangeFromTo={doExchangeFromTo}
          // showCitySelector={doShowCitySelector}
          {...cbs}
        />
        <DepartDate />
        <HighSpeed />
        <Submit />
      </form>
      <CitySelector
        show={isCitySelectorVisible}
        cityData={cityData}
        isLoading={isLoadingCItyData}
        {...citySelectorCbs}
      />

    </div>
  )


}

export default connect(
  function mapStateToProps(state) {
    return state
  },
  function mapDispatchToProps(dispatch) {
    return { dispatch }
  }
)(App);
